<?php
/**
 * Created by PhpStorm.
 * Author: Shadow
 * Date: 2021/12/28
 * Time: 10:53 上午
 * description: Base.php
 */


declare (strict_types=1);

namespace app\adminapi\middleware;

use think\facade\Log;
use think\Request;

class Base
{
    /**
     * 日志中保存了全部的请求信息，保存了请求地址 请求方法 请求路由  请求头  请求参数
     * Base constructor.
     */
    public function __construct()
    {
        $request = app(Request::class);
        $requestInfo = [
            'ip' => $request->ip(),
            'method' => $request->method(),
            'host' => $request->host(),
            'uri' => $request->url(),
        ];
        $logInfo = [
            "{$requestInfo['ip']} {$requestInfo['method']} {$requestInfo['host']}{$requestInfo['uri']}",
            '[ ROUTE ] ' . var_export($this->getRouteInfo(), true),
            '[ HEADER ] ' . var_export($request->header(), true),
            '[ PARAM ] ' . var_export($request->param(), true),
            '---------------------------------------------------------------',
        ];
        $logInfo = implode(PHP_EOL, $logInfo) . PHP_EOL;
        Log::record($logInfo, 'info');
    }

    /**
     * 获取路由信息
     * @return array
     */
    protected function getRouteInfo(): array
    {
        $request = app(Request::class);
        return [
            'rule' => $request->rule()->getRule(),
            'route' => $request->rule()->getRoute(),
            'option' => $request->rule()->getOption(),
            'var' => $request->rule()->getVars(),
        ];
    }
}